package cn.wp.common.core.web.client;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.wp.common.core.WpVar;
import cn.wp.common.core.exception.WpException;
import lombok.Data;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 服务请求类
 * Created by chenyb on 2019/10/15
 */
@Data
public class ServiceRequest {

    // 服务名
    private String serviceInstanceName;

    // 服务协议
    private String serviceInstanceProtocol;

    // 服务单元名称
    private String serviceUnitName;

    // 服务完整地址
    private String serviceUrl;

    // 负载均衡
    private boolean loadBalance;

    // 返回值类型
    // private Class<?> returnType;

    // 返回值类型
    // for example: new ParameterizedTypeReference<List<DemoDto>>(){}
    private ParameterizedTypeReference returnType;

    // 仅返回数据,不包裹WpResult对象
    private boolean returnDataOnly = true;

    private MultiValueMap<String,Object> parameterMap = new LinkedMultiValueMap<>();

    public ServiceRequest addParam(String key,Object value){
        parameterMap.add(key,value);
        return this;
    }

    public ServiceRequest addAll(MultiValueMap<String,Object> multiValueMap){
        parameterMap.addAll(multiValueMap);
        return this;
    }

    public String getServiceUrl() {
        // 优先使用直接指定serviceUrl
        if(serviceUrl != null){
            return serviceUrl;
        }

        // 使用配置构造请求地址
        return serviceInstanceProtocol + "://" + serviceInstanceName + serviceUnitName;
    }

    /**
     * 构建查询参数
     * @return
     */
    public String buildQueryString(){
        StringBuilder stringBuilder = new StringBuilder();
        Set<Map.Entry<String, List<Object>>> entries = parameterMap.entrySet();
        int index = 0;
        try {
            for(MultiValueMap.Entry<String,List<Object>> entry : parameterMap.entrySet()){
                String key = entry.getKey();
                List<Object> valueList = entry.getValue();
                for(Object o : valueList){
                    if(index == 0) {
                        stringBuilder.append("?");
                    } else  {
                        stringBuilder.append("&");
                    }
                    //stringBuilder.append(key + "=" + URLEncoder.encode(String.valueOf(o), WpVar.ENCODE));
                    stringBuilder.append(key + "=" + o);
                    index++;
                }
            }
        } catch (Exception e) {
            throw new WpException("buildQueryString error",e);
        }

        return stringBuilder.toString();
    }

}
